package mysql.ddl.queries;

import mysql.Column;
import mysql.Schema;
import mysql.Table;
import mysql.commands.SqlCommand;

import mysql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;

import static mysql.ddl.SqlStrategy.LOAD_FILE;

/**
 * Created by nuno-rafael-figueiredo on 01-07-2014.
 */
public class SelectFks extends SqlCommand {
    private Schema schema;

    public SelectFks(Connection connection, Schema schema) {
        super(connection, LOAD_FILE);
        this.schema = schema;
    }

    @Override
    public void execute() {
        try{
            ResultSet resultSet = connection.executeQuery(getSql());
            while (resultSet.next()) {
                String name = resultSet.getString(1);

                Table table1 = schema.getTable(resultSet.getString(2));
                Column column1 = table1.getColumn(resultSet.getString(3));

                Table table2 = schema.getTable(resultSet.getString(4));
                Column column2 = table2.getColumn(resultSet.getString(5));

                column1.reference(name, table2, column2);
            }

            finish();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
